'use client'

import { FormEventHandler, useState, useMemo } from 'react'
import Image, { StaticImageData } from 'next/image'
import Schema from 'async-validator'
import { fetcher } from '@/src/utils/fetcher'
import { objectToQueryString } from '@/src/utils/object-to-query-string'

import profileIcon from '@/public/profile_gray_fill.png'
import phoneIcon from '@/public/phone_gray_fill.png'
import emailIcon from '@/public/email_gray_fill.png'
import Overlay from '@/src/app/components/overlay'
import Modal from '@/src/app/components/modal'
import { submit } from '@/src/app/actions/submit'

import pen from '@/public/pen_hero.png'
import penBg from '@/public/message_pen_bg.png'

interface CellProps {
  value: string
  icon: StaticImageData
  placeholder: string
  onInput: FormEventHandler
}

const Cell: React.FC<CellProps> = (props) => {
  const { value, icon, placeholder, onInput } = props
  const [isFocus, setIsFocus] = useState(false)
  return (
    <div
      className={`flex items-center border-b-solid border-b-[1px] transition-colors duration-300 ${
        isFocus ? 'border-b-[#000000]' : 'border-b-[##EAEAEA]'
      }`}
    >
      <input
        value={value}
        type='text'
        className={`flex-1 w-full py-[1.25rem] bg-transparent placeholder:text-[#999999] text-[#333333] text-[0.875rem] leading-[0.875rem] outline-none lg:py-[0.8125rem] 2xl:py-[1.25rem] 2xl:text-[1.125rem] 2xl:leading-[1.5rem]`}
        placeholder={placeholder}
        onInput={onInput}
        onFocus={() => setIsFocus(true)}
        onBlur={() => setIsFocus(false)}
      />
      <div className='relative w-[0.875rem] h-[0.875rem] 2xl:w-[1.125rem] 2xl:h-[1.125rem]'>
        <Image src={icon} alt='icon' fill sizes='(max-width: 1024px) 5vw' />
      </div>
    </div>
  )
}

interface FormProps {
  contentLabel: string
  buttonLabel: string
  placeholders: {
    name: string
    mobile: string
    email: string
    content: string
  }
  modalTitle: string
  modalContent: string
}

const Form: React.FC<FormProps> = (props) => {
  const { contentLabel, buttonLabel, placeholders, modalTitle, modalContent } =
    props

  const [isShowSuccessModal, setIsShowSuccessModal] = useState(false)

  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    email: '',
    content: '',
  })

  const validator = useMemo(() => {
    const rules = {
      name: {
        type: 'string',
        required: true,
        message: 'Your name is required.',
      },
      phone: {
        type: 'string',
        required: true,
        message: 'Phone number is required.',
      },
      email: {
        type: 'string',
        required: true,
        message: 'Email is required.',
      },
      content: {
        type: 'string',
        required: true,
        message: 'Consulation content is required.',
      },
    }

    const validator = new Schema(rules as any)

    return validator
  }, [])

  const handleInput = (value: string, field: string) => {
    setFormData({
      ...formData,
      [field]: value,
    })
  }

  const handleSubmit = async () => {
    validator.validate(formData, async (errors, fields) => {
      if (errors) {
        alert(errors[0].message)
        return
      }

      const result = await submit({ ...formData, type: 'message' })

      if (result) {
        setIsShowSuccessModal(true)
        setFormData({ name: '', phone: '', email: '', content: '' })
      } else {
        alert('Error')
      }
    })
  }

  return (
    <>
      <div className='relative bg-[#F8F8F8] lg:w-full'>
        {/* 右侧黑色背景 */}
        <div className='absolute z-0 right-0 top-0 bottom-0 overflow-hidden w-[5.28125rem] lg:w-[11.125rem] 2xl:w-[14rem]'>
          <div className='absolute right-0 top-0 bottom-0 w-[52vw] lg:w-[12.5rem]'>
            <Image
              src={penBg}
              alt='pen bg'
              fill
              sizes='(max-width: 1024px) 52vw'
            />
          </div>
        </div>
        <div className='relative z-10 mr-[5.28125rem] pr-[3.5rem] lg:mr-[11.125rem] 2xl:mr-[14rem] bg-[#f8f8f8]'>
          <div className='w-full mx-[0.9375rem] lg:mx-5 lg:max-w-[18.1875rem] 2xl:mx-[1.8125rem] 2xl:my-2 2xl:max-w-[22.6875rem]'>
            <Cell
              value={formData.name}
              icon={profileIcon}
              placeholder={placeholders.name}
              onInput={(e) =>
                handleInput((e.target as HTMLInputElement).value, 'name')
              }
            />
            <Cell
              value={formData.phone}
              icon={phoneIcon}
              placeholder={placeholders.mobile}
              onInput={(e) =>
                handleInput((e.target as HTMLInputElement).value, 'phone')
              }
            />
            <Cell
              value={formData.email}
              icon={emailIcon}
              placeholder={placeholders.email}
              onInput={(e) =>
                handleInput((e.target as HTMLInputElement).value, 'email')
              }
            />
            <div className='py-[1.25rem]'>
              <div className='text-[#999999] text-[0.875rem] leading-[1.25rem] 2xl:text-[1.125rem] 2xl:leading-[1.5rem]'>
                {contentLabel}
              </div>
              <div className='h-2 2xl:h-4'></div>
              <textarea
                value={formData.content}
                className='px-[0.5rem] py-[0.625rem] bg-white w-full text-[#333333] text-[0.875rem] leading-[1.0625rem] placeholder:text-[#999999] outline-none min-h-[4.84375rem] 2xl:px-4 2xl:py-2 2xl:text-[1rem] 2xl:leading-[2rem]'
                placeholder={placeholders.content}
                onInput={(e) =>
                  handleInput((e.target as HTMLInputElement).value, 'content')
                }
              />
            </div>
            <div className='flex justify-center items-center'>
              <button
                className='text-white text-[0.875rem] leading-[1.25rem] px-[0.9375rem] py-[0.6875rem] bg-black uppercase'
                onClick={handleSubmit}
              >
                {buttonLabel}
              </button>
            </div>
          </div>
          <div className='h-[1.125rem]'></div>
        </div>
        <div className='absolute z-10 -right-[4.3%] bottom-[15.58%] w-[13.0625rem] h-[10.6875rem] lg:right-[4%] lg:w-[20.6875rem] lg:h-[14.3125rem] 2xl:w-[31.0625rem] 2xl:h-[21.4375rem] 2xl:right-[-4%] 2xl:bottom-[3.0625rem]'>
          <Image
            src={pen}
            alt='pen image'
            fill
            sizes='(max-width: 1024px) 15.2vw'
          />
        </div>
      </div>
      <Overlay isOpen={isShowSuccessModal} setIsOpen={setIsShowSuccessModal}>
        <Modal
          setIsOpen={setIsShowSuccessModal}
          title={modalTitle}
          content={modalContent}
        />
      </Overlay>
    </>
  )
}

export default Form
